<template>
  <div class="admin-dashboard-container">
    <div class="header-section">
      <div class="header-bg-shape"></div>
      <div class="header-content-wrapper">
        <div class="header-text-area">
          <h1 class="header-title">
            <el-icon class="title-icon">
              <List />
            </el-icon>
            教室借用审批
          </h1>
          <p class="header-subtitle">
            <el-icon :size="14" class="quote-icon">
              <List />
            </el-icon>
            管理员可查看、搜索、审批教室借用申请
          </p>
        </div>
        <div class="header-actions">
          <el-input v-model="teacherKeyword" placeholder="按教师姓名搜索" @input="fetchApplications" clearable class="search-input" style="width: 180px;" />
          <el-input v-model="classroomKeyword" placeholder="按教室编号搜索" @input="fetchApplications" clearable class="search-input" style="width: 180px; margin-left: 12px;" />
          <el-select v-model="statusFilter" class="status-select" style="width: 140px; margin-left: 12px;" @change="fetchApplications">
            <el-option label="全部" :value="''" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
            <el-option label="待审批" :value="0" />
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 340px; margin-left: 12px;"
            @change="fetchApplications"
          />
        </div>
      </div>
    </div>

    <el-card class="data-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List />
          </el-icon>
          <span>借用申请列表</span>
        </div>
      </template>
      <el-table :data="applications" style="width: 100%" class="teacher-table" v-loading="loading">
        <el-table-column prop="id" label="申请ID" width="80" />
        <el-table-column prop="teacherName" label="教师姓名" width="120" />
        <el-table-column prop="classroomNumber" label="教室编号" width="120" />
        <el-table-column prop="applyTime" label="申请时间">
          <template #default="scope">
            {{ formatApplyTime(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="审批时间">
          <template #default="scope">
            {{ formatApplyTime(scope.row.reviewTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">待审批</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <template v-if="scope.row.status === 0">
              <el-button size="small" type="success" @click="handleReview(scope.row.id, 1)">
                通过
              </el-button>
              <el-button size="small" type="danger" @click="openRejectDialog(scope.row)">
                拒绝
              </el-button>
            </template>
            <template v-else>
              <el-button size="small" @click="openDetailDialog(scope.row)">查看信息</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="rejectDialogVisible" append-to-body title="填写拒绝原因" width="400px">
      <el-input v-model="rejectRemark" type="textarea" rows="3" placeholder="请输入拒绝原因" />
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">确定拒绝</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="detailDialogVisible" append-to-body title="审批详细信息" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请ID">{{ detailRow?.id }}</el-descriptions-item>
        <el-descriptions-item label="教师姓名">{{ detailRow?.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="教室编号">{{ detailRow?.classroomNumber }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatApplyTime(detailRow?.applyTime) }}</el-descriptions-item>
        <el-descriptions-item label="审批时间">{{ formatApplyTime(detailRow?.reviewTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailRow?.status === 0" type="info">待审批</el-tag>
          <el-tag v-else-if="detailRow?.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="detailRow?.status === 2" type="danger">已拒绝</el-tag>
          <el-tag v-else>未知</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailRow?.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { List, Search } from '@element-plus/icons-vue';
import { getAllReviewedBookings, getBookingsByTeacherName, getBookingsByRoomNumber, reviewClassroomApplication } from '@/services/classroomService';
import { useAuthStore } from '@/stores/authStore';

const applications = ref([]);
const teacherKeyword = ref('');
const classroomKeyword = ref('');
const statusFilter = ref('');
const dateRange = ref([]);
const loading = ref(false);
const authStore = useAuthStore();

const fetchApplications = async () => {
  loading.value = true;
  try {
    let data = [];
    // 统一获取全部数据
    const res = await getAllReviewedBookings();
    data = res.data.data || [];
    // 教师名筛选
    if (teacherKeyword.value) {
      data = data.filter(item => (item.teacherName || '').includes(teacherKeyword.value));
    }
    // 教室编号筛选
    if (classroomKeyword.value) {
      data = data.filter(item => (item.classroomNumber || '').toString().includes(classroomKeyword.value));
    }
    // 状态筛选
    if (statusFilter.value !== '' && statusFilter.value !== undefined) {
      data = data.filter(item => String(item.status) === String(statusFilter.value));
    }
    // 时间区间筛选（精确到小时）
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      data = data.filter(item => {
        let applyDateTime = '';
        if (Array.isArray(item.applyTime) && item.applyTime.length >= 3) {
          const [y, m, d, h = 0, min = 0, s = 0] = item.applyTime;
          const pad = n => n.toString().padStart(2, '0');
          applyDateTime = `${y}-${pad(m)}-${pad(d)} ${pad(h)}:${pad(min)}:${pad(s)}`;
        } else if (typeof item.applyTime === 'string') {
          applyDateTime = item.applyTime.slice(0, 19);
        }
        return applyDateTime >= start && applyDateTime <= end;
      });
    }
    applications.value = data;
  } catch (e) {
    ElMessage.error('获取申请列表失败');
  } finally {
    loading.value = false;
  }
};

const rejectDialogVisible = ref(false);
const rejectRemark = ref('');
const rejectRow = ref(null);
const detailDialogVisible = ref(false);
const detailRow = ref(null);

function openRejectDialog(row) {
  rejectRow.value = row;
  rejectRemark.value = '';
  rejectDialogVisible.value = true;
}

function confirmReject() {
  if (!rejectRemark.value) {
    ElMessage.warning('请填写拒绝原因');
    return;
  }
  handleReview(rejectRow.value.id, 2, rejectRemark.value);
  rejectDialogVisible.value = false;
}

function openDetailDialog(row) {
  detailRow.value = row;
  detailDialogVisible.value = true;
}

const handleReview = async (bookingId, status, remark) => {
  try {
    await reviewClassroomApplication({
      bookingId,
      status,
      reviewerId: authStore.userInfo?.id || 1,
      remark: status === 1 ? '审核通过' : (remark || '')
    });
    ElMessage.success(status === 1 ? '审批通过' : '已拒绝该申请');
    fetchApplications();
  } catch (e) {
    ElMessage.error('审批失败');
  }
};

function formatApplyTime(val) {
  if (Array.isArray(val) && val.length >= 3) {
    const [y, m, d, h = 0, min = 0, s = 0] = val;
    const pad = n => n.toString().padStart(2, '0');
    return `${y}-${pad(m)}-${pad(d)} ${pad(h)}:${pad(min)}:${pad(s)}`;
  }
  return val ?? '';
}

onMounted(fetchApplications);
</script>

<style scoped>
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.admin-dashboard-container {
  padding: 40px 0 40px 0;
  background: linear-gradient(135deg, #e0e7ef 60%, #f8fafc 100%);
  min-height: calc(100vh - var(--header-height, 60px));
}
.header-section {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 56px 56px 44px 56px;
  margin-bottom: 36px;
  border-radius: 36px;
  overflow: hidden;
  color: #fff;
  background: rgba(40, 80, 220, 0.55);
  box-shadow: 0 16px 48px -12px rgba(30, 58, 138, 0.18);
  min-height: 240px;
  animation: fadeInUp 0.6s cubic-bezier(.4,2,.6,1) backwards;
  backdrop-filter: blur(18px) saturate(1.2);
  border: 1.5px solid rgba(255,255,255,0.18);
}
.header-bg-shape {
  position: absolute;
  top: -60px;
  right: -100px;
  width: 380px;
  height: 380px;
  background: linear-gradient(135deg, rgba(255,255,255,0.18), rgba(255,255,255,0));
  border-radius: 50%;
  filter: blur(24px);
  z-index: 1;
}
.header-content-wrapper {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 32px;
  flex: 1;
  align-items: flex-start;
}
.header-text-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.header-title {
  font-size: 2.8rem;
  font-weight: 900;
  margin: 0;
  color: #fff;
  text-shadow: 0 8px 24px rgba(0,0,0,0.13);
  display: flex;
  align-items: center;
  letter-spacing: 1.5px;
}
.title-icon {
  margin-right: 22px;
  font-size: 2.8rem;
  color: #fff;
  filter: drop-shadow(0 2px 8px #2563eb88);
}
.header-subtitle {
  font-size: 1.18rem;
  color: #e0f2fe;
  opacity: 0.95;
  margin: 0;
  max-width: 700px;
  display: flex;
  align-items: flex-start;
  font-weight: 400;
  letter-spacing: 0.5px;
}
.quote-icon {
  flex-shrink: 0;
  margin-right: 14px;
  margin-top: 2px;
  color: #bae6fd;
}
.header-actions {
  display: flex;
  gap: 22px;
  margin-top: 16px;
  align-items: center;
}
.search-input {
  max-width: 240px;
  border-radius: 24px;
  background: rgba(255,255,255,0.22);
  box-shadow: 0 2px 12px rgba(30,58,138,0.08);
  border: 1.5px solid rgba(255,255,255,0.18);
  backdrop-filter: blur(6px);
}
.status-select {
  border-radius: 24px;
  background: rgba(255,255,255,0.22);
  border: 1.5px solid rgba(255,255,255,0.18);
}
.el-date-picker {
  border-radius: 24px;
  background: rgba(255,255,255,0.22);
  border: 1.5px solid rgba(255,255,255,0.18);
}
.data-card {
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(30,58,138,0.10);
  animation: fadeInUp 0.7s cubic-bezier(.4,2,.6,1) backwards;
  background: rgba(255,255,255,0.82);
  backdrop-filter: blur(8px);
  border: 1.5px solid rgba(40,80,220,0.08);
}
.data-card .card-header {
  font-weight: 800;
  display: flex;
  align-items: center;
  font-size: 1.22rem;
  color: var(--el-text-color-primary);
  letter-spacing: 1.2px;
}
.data-card .card-header .el-icon {
  margin-right: 12px;
  color: #2563eb;
  filter: drop-shadow(0 2px 8px #2563eb33);
}
.teacher-table {
  border-radius: 14px;
  overflow: hidden;
  font-size: 1.08rem;
  background: transparent;
}
.teacher-table :deep(.el-table__header-wrapper th) {
  background-color: rgba(241,245,249,0.85);
  color: #64748b;
  font-weight: 800;
  font-size: 1.08rem;
  letter-spacing: 0.5px;
}
.teacher-table :deep(.el-table__row) {
  transition: background-color 0.22s cubic-bezier(.4,2,.6,1);
  height: 60px;
  font-size: 1.08rem;
  font-weight: 500;
  letter-spacing: 0.2px;
}
.teacher-table :deep(.el-table__row:hover) {
  background-color: rgba(96,165,250,0.10);
}
.teacher-table :deep(.el-button) {
  border-radius: 22px;
  font-weight: 600;
  padding: 8px 22px;
  transition: all 0.18s;
  font-size: 1.02rem;
  letter-spacing: 0.5px;
}
.teacher-table :deep(.el-button--success) {
  background: linear-gradient(90deg,#22d3ee,#2563eb);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px #2563eb22;
}
.teacher-table :deep(.el-button--danger) {
  background: linear-gradient(90deg,#f43f5e,#f59e42);
  border: none;
  color: #fff;
  box-shadow: 0 2px 8px #f43f5e22;
}
.teacher-table :deep(.el-button:hover) {
  filter: brightness(1.10) saturate(1.2);
  transform: translateY(-2px) scale(1.06);
  box-shadow: 0 6px 18px #2563eb33;
}
.teacher-table :deep(.el-tag) {
  border-radius: 12px;
  font-size: 1.02rem;
  padding: 4px 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
  box-shadow: 0 2px 8px #2563eb11;
}
.el-dialog {
  border-radius: 22px !important;
  box-shadow: 0 12px 48px rgba(30,58,138,0.13);
  background: rgba(255,255,255,0.92);
  backdrop-filter: blur(12px);
  border: 1.5px solid rgba(40,80,220,0.10);
}
.el-dialog__header {
  border-top-left-radius: 22px;
  border-top-right-radius: 22px;
  background: rgba(241,245,249,0.85);
  color: #2563eb;
  font-weight: 800;
  font-size: 1.18rem;
}
.el-dialog__footer {
  background: rgba(249,250,251,0.85);
  border-bottom-left-radius: 22px;
  border-bottom-right-radius: 22px;
}
.el-descriptions {
  background: rgba(248,250,252,0.92);
  border-radius: 16px;
  padding: 12px 0;
  font-size: 1.08rem;
}
.el-descriptions__label {
  color: #2563eb;
  font-weight: 700;
  letter-spacing: 0.5px;
}
.el-descriptions__content {
  color: #334155;
  font-weight: 500;
}
</style>
